<?php

namespace App\Api\Controllers;

use App\Http\Controllers\WeChat\WxTrait;
use App\Models\BalanceRecord;
use App\Models\Withdraw;
use Dingo\Api\Http\Request;
use Dingo\Api\Routing\Helpers;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;

/**
 * Class SpreadController
 * @package App\Api\Controllers
 * 提现申请
 */
class WithdrawController extends Controller
{
    use Helpers;
    use WxTrait;

    /**
     * 名称：提现首页数据展示
     */
    public function index(){
        $user=$this->auth->user();
        $pageList=Withdraw::where('user_id',$user->id)->get();//当前用户提现记录
        return $this->response->array([
            'status_code'=>200,
            'message'=>'获取数据成功',
            'result'=>[
                'pageData'=>[
                    'nickname'=>deal_emoji($user->nickname),
                    'head_img'=>$user->head_img,
                    'id'=>$user->id,
                    'balance'=>$user->balance,
                    ],
                'pageList'=>$pageList
            ]
        ]);
    }

    /**
     * 名称：申请提现
     * 任务：1.生成提现记录，扣掉用户余额。
     */
    public function store(Request $request){
        $user=$this->auth->user();
        if(!$request->withdrawNum || $request->withdrawNum>$user->balance){
            return $this->response->array([
                'status_code'=>201,
                'message'=>'提现金额不合法',
            ]);
        }
        $haveWithdraw=Withdraw::where([['user_id',$user->id],['withdraw_status',0]])->first();
        if($haveWithdraw){
            return $this->response->array([
                'status_code'=>201,
                'message'=>'您有提现记录还未通过，不能发起提现',
            ]);
        }
        $rollback=false;//回滚标志
        DB::beginTransaction();//开启事物
        //入库数据
        $dataIn=[
            'user_id'=>$user->id,
            'amount'=>$request->withdrawNum,
            'fail_info'=>'',
            'withdraw_status'=>0,
            'manager_id'=>'',
            'wx'=>$request->wx,//微信号
            'code'=>rand(1000,9999)//提现码
        ];
        //生成提现记录
        $withdraw=Withdraw::create($dataIn);
        if(!$withdraw){
            $rollback='1.申请提现失败';
            goto down;
        }
        //扣除用户余额
        $user->balance-=$withdraw->amount;
        if(!$user->save()){
            $rollback='2.申请提现失败';
            goto down;
        }
        //记录日志
        if(!BalanceRecord::create([
            'user_id'=>$user->id,
            'amount'=>$withdraw->amount,
            'description'=>"提现申请提交成功，余额扣除",
            'type'=>1,//提现
            'action'=>'-'])){
            $rollback='记录余额日志失败';
            goto down;
        }


        down:
        if($rollback){
            DB::rollback();
            return $this->response->array([
                'status_code'=>201,
                'message'=>$rollback,
            ]);
        }else{
            DB::commit();
        }
        //推送模板消息给管理元处理
        $needDealNum=Withdraw::where('withdraw_status',0)->count();
        $content=[
            'first'=>'提现申请处理',
            'keyword1'=>'需要处理',
            'keyword2'=>'未处理',
            'keyword3'=>'请您尽快登录管理平台，审核用户提现',
            'remark'=>'待处理数量:'.$needDealNum.'条'
        ];
        $managerOpenids=DB::table('users')->where('manager',1)->pluck('openid');
        if(count($managerOpenids)!=0){
            //存在管理元，则发送模板消息通知管理员
            if(count($managerOpenids)!=0){
                foreach($managerOpenids as $v){
                    $this->prepareMessage($v,2,$content);
                }

            }
        }
        return $this->response->array([
            'status_code'=>200,
            'message'=>'已提交申请',
        ]);
    }

    /**
     * 名称：用户重新提交申请
     * 必要条件：记录状态为失败
     */
    public function update(Request $request){
        if(!$request->withdrawId){
            return $this->response->array([
                'status_code'=>201,
                'message'=>'错误请求',
            ]);
        }
        $user=$this->auth->user();
        $withdraw=Withdraw::find($request->withdrawId);
        if(!$withdraw || $withdraw->user_id!=$user->id || $withdraw->withdraw_status!=2){
            return $this->response->array([
                'status_code'=>201,
                'message'=>'抱歉，您没有权限进行此操作',
            ]);
        }

        $rollback=false;//回滚标志
        DB::beginTransaction();//开启事物
        $withdraw->withdraw_status=0;//待处理
        if(!$withdraw->save()){
            $rollback='1.申请提现失败';
            goto down;
        }

        //扣除用户余额
        $user->balance-=$withdraw->amount;
        if($user->balance<0){
            //检查用户余额
            $rollback='3.申请提现失败';
            goto down;
        }

        if(!$user->save()){
            $rollback='3.申请提现失败';
            goto down;
        }

        //记录日志
        if(!BalanceRecord::create([
            'user_id'=>$user->id,
            'amount'=>$withdraw->amount,
            'description'=>"提交提现申请成功，余额扣除",
            'type'=>1,
            'action'=>'-'])){
            $rollback='记录余额日志失败';
            goto down;
        }


        down:
        if($rollback){
            DB::rollback();
            return $this->response->array([
                'status_code'=>201,
                'message'=>$rollback,
            ]);
        }else{
            DB::commit();
        }
        //推送模板消息给管理元处理
        $needDealNum=Withdraw::where('withdraw_status',0)->count();
        $content=[
            'first'=>'提现申请处理',
            'keyword1'=>'需要处理',
            'keyword2'=>'未处理',
            'keyword3'=>'请您尽快登录管理平台，审核用户提现',
            'remark'=>'待处理数量:'.$needDealNum.'条'
        ];
        $managerOpenids=DB::table('users')->where('manager',1)->pluck('openid');
        if(count($managerOpenids)!=0){
            //存在管理元，则发送模板消息通知管理员
            if(count($managerOpenids)!=0){
                foreach($managerOpenids as $v){
                    $this->prepareMessage($v,2,$content);
                }

            }
        }
        return $this->response->array([
            'status_code'=>200,
            'message'=>'已重新提交申请',
        ]);


    }

}